/**
 * @author Aaron
 * @createTime 14:17 2022/6/3
 **/
package db_main

import (
	"errors"
	"fmt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"

	"gorm.io/gorm"
)

func GetNobleRecordPrice(uid uint) (*models_main.NobleRecord, error) {
	o := &models_main.NobleRecord{}
	err := mysql.GetRTable(&models_main.NobleRecord{}).
		Raw("SELECT r.id AS id, r.expiration, n.renew_price AS renew_price"+
			",r.noble_id AS noble_id, n.`name`,n.rank_id, n.`name`,n.rank_id FROM db_noble_record r"+
			" LEFT JOIN db_noble n ON n.id = r.noble_id WHERE "+
			"r.uid = ? AND r.expiration >? ORDER BY n.weight DESC",
			uid, time.Now().Unix()).
		First(o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, nil
}

func GetNobleRecord(uid uint) (*models_main.NobleRecord, error) {
	o := &models_main.NobleRecord{}
	err := mysql.GetRTable(&models_main.NobleRecord{}).
		Where("uid = ? AND expiration > ?", uid, time.Now().Unix()).
		Joins("LEFT JOIN db_noble n ON n.id =db_noble_record.noble_id").
		Order("n.id DESC").Limit(1).
		Find(o).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = nil
	}
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, nil
}

func InsertNobleRecordByTx(tx *gorm.DB, nr *models_main.NobleRecord) error {
	err := tx.Model(&models_main.NobleRecord{}).Create(nr).Error
	if err != nil {
		tx.Rollback()
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}

func UpdateNobleRecordByTx(tx *gorm.DB, nr *models_main.NobleRecord) error {
	err := tx.Where("id", nr.Id).Updates(nr).Error
	if err != nil {
		tx.Rollback()
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return nil
}

/*
func GetNobleRecordByUid(uid int) (*api_models.NobleRecordRes, error) {
	resp := &api_models.NobleRecordRes{}
	err := global.GetR().Raw(
		"SELECT db_noble_record.*,db_noble.`name`,db_noble.rank_id "+
			"FROM db_noble_record LEFT JOIN db_noble "+
			"ON db_noble.id=db_noble_record.noble_id "+
			"WHERE db_noble_record.uid=? AND db_noble_record.anchor_id=0 "+
			"ORDER BY db_noble_record.create_time DESC", uid).Scan(resp).Error
	return resp, err
}
*/
